<template>
  <el-select v-model="select" ref="selectElement" popper-class="dept-tree-select" @visible-change="handleSelect">
    <template #footer>
      <el-scrollbar max-height="300px">
        <el-tree :key="key" :data="store.deptTree" @node-click="handleNodeClick" :highlight-current="true" />
      </el-scrollbar>
    </template>
  </el-select>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import store from '../../store/deptTree'

defineOptions({
  name: 'a-dept'
})

const selectElement = ref<SelectInstance | null>(null)

const model = defineModel<unknown>({ required: true })
const select = defineModel<string>('value')
const key = ref('')

function handleSelect() {
  if (select.value) return
  key.value = Date.now().toString()
}

function handleNodeClick(data: DeptTree) {
  model.value = data.id
  select.value = data.label
  const e = selectElement.value!.$el
  e.getElementsByTagName('input')[0].click()
}

watch(
  () => [model.value, select.value],
  () => {
    if (!model.value) select.value = ''
    if (!select.value) model.value = ''
  }
)
</script>

<style lang="scss">
.dept-tree-select {
  overflow: hidden;
  .el-select-dropdown__footer {
    border-top: 0px;
    padding: 0;
  }
  .el-select-dropdown__empty {
    display: none;
  }
}
</style>
